﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Castle.DynamicProxy;

namespace Selenium.PageToolkit.ControlFactoryChainImpl
{
    public abstract class ChainBase<TAttribute> : IControlFactoryChain
    {

        public IList<Type> GetSupportedAttributeTypes()
        {
            var list = Next == null ? new List<Type>() : Next.GetSupportedAttributeTypes();
            list.Add(typeof(TAttribute));
            return list;
        }

        protected abstract object Inject(Type fieldType, TAttribute attribute, LambdaPageFactory factory);
        public object Inject(Type fieldType, object attribute, LambdaPageFactory factory)
        {
            if (attribute is TAttribute)
            {
                object result = Inject((Type)((MemberInfo)fieldType), (TAttribute)attribute, factory);
                if (result != null)
                    return result;
            }
            if (Next != null)
                return Next.Inject(fieldType, attribute, factory);
            return null;
        }

        public IControlFactoryChain Next { set; private get; }
    }
}